class SitesController < ApplicationController

  def show
    @site = Site.find(params[:id])
    return self.unauthorized unless self.current_user.can('view:site', @site)
    @groups = @site.groups
    add_page_token(@site.name)
  end

  def new
    return self.unauthorized unless self.current_user.can('create:site', nil)
    @site = Site.new
  end

  def edit
    @site = Site.find(params[:id])
    return self.unauthorized unless self.current_user.can('edit:site', @site)
    add_page_token(@site.name)
  end

  def create
    @site = Site.new(params[:site])
    return self.unauthorized unless self.current_user.can('create:site', @site)
    @site.program = @program

    if @site.save
      flash[:notice] = 'Site was successfully created.'
      redirect_to(@site)
    else
      render :action => "new"
    end
  end

  def update
    @site = Site.find(params[:id])
    return self.unauthorized unless self.current_user.can('edit:site', @site)
    add_page_token(@site.name)

    if @site.update_attributes(params[:site])
      flash[:notice] = 'Site was successfully updated.'
      redirect_to(@site)
    else
      render :action => "edit"
    end
  end

  def destroy
    @site = Site.find(params[:id])
    return self.unauthorized unless self.current_user.can('delete:site', @site)
    @site.destroy

    redirect_to home_path
  end

  def route
	  @site = Site.find(params[:id])
	  return self.unauthorized unless self.current_user.can('edit:site', @site)
	  add_page_token(@site.name)

	  @routes = Routesite.siteRoutes(@site)
	  if request.post?
		  @routes.each do |r|
			  r.updateSiteRoute(@site.id,params['route'+r.id.to_s])
		  end
		  #reload
		  @routes = Routesite.siteRoutes(@site)
		  flash[:notice] = "Site route order changed."
	  end
  end

end
